package common

import (
	"context"
	"gozero-demo/internal/constants"
	"gozero-demo/internal/svc"
	"gozero-demo/internal/types"
	"gozero-demo/internal/utils"
	"sort"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type SimpleSelectLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 公共信息
func NewSimpleSelectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SimpleSelectLogic {
	return &SimpleSelectLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// 定义结构体
type Item struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

func mapToSortedSlice(m map[int]string) []Item {
	// 提取所有的key
	keys := make([]int, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}

	// 对key进行排序
	sort.Ints(keys)

	// 根据排序后的key顺序，将key和value组合成结构体切片
	sortedSlice := make([]Item, 0, len(m))
	for _, k := range keys {
		sortedSlice = append(sortedSlice, Item{ID: k, Name: m[k]})
	}

	return sortedSlice
}

func formatSlice(m [][]string) []Item {
	// 根据排序后的key顺序，将key和value组合成结构体切片
	sortedSlice := make([]Item, 0, len(m))
	for _, v := range m {
		id, _ := strconv.Atoi(v[0])
		sortedSlice = append(sortedSlice, Item{ID: id, Name: v[1]})
	}

	return sortedSlice
}

func (l *SimpleSelectLogic) SimpleSelect(req *types.SimpleSelectRequest) (resp *utils.Response, err error) {
	paramType := req.Type
	var data interface{}
	switch paramType {
	case "country":
		//data = mapToSortedSlice(constants.CountryMap) //使用map
		//data = formatSlice(constants.CountrySlice) //使用切片
		data = constants.CountryStruct //使用结构体
	case "others":
		data = nil
	}
	//成功返回
	return utils.SuccessResponse(data), nil
}
